package com.coffee.wx.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coffee.wx.entity.business.WxFollowInfo;
import com.coffee.wx.entity.business.WxUser;
import com.coffee.wx.enums.QrCodeTypeEnum;
import com.coffee.wx.service.IActivityService;
import com.coffee.wx.service.IWxFollowInfoService;
import com.coffee.wx.service.IWxUserService;
import com.coffee.wx.uitls.ImageUtils;
import com.coffee.wx.uitls.wx.WxMaterialUtils;
import com.coffee.wx.uitls.wx.WxQrCodeUtils;
import com.coffee.wx.uitls.wx.WxSendMsgUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
public class ActivityServiceImpl implements IActivityService {

    private final String APPID = "wx1679fc8e56c3f821";

    public static final String ACTIVITY_KEY = "activity:";

    // 用户登录授权地址
    private static final String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=%s&scope=%s&state=%s#wechat_redirect";

    // 用户授权回调地址
    private static final String REDIRECT_URI = "i79a8m.natappfree.cc";

    @Resource
    private IWxUserService userService;

    @Resource
    private IWxFollowInfoService followInfoService;

    @Override
    public String signUp() {

        String responseType = "code";
        String scope = "snsapi_userinfo";
        String state = "STATE";
        String encodeUrl = null;
        try {
            encodeUrl = URLEncoder.encode("http://" + REDIRECT_URI + "/getSignUpUserInfo", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String url = String.format(AUTHORIZE_URL, APPID, encodeUrl, responseType, scope, state);

        return String.format("点击链接 <a href=\"%s\">参与活动</a>", url);
    }

    @Override
    public String getPoster(String fromUserName) {
        String qrCodeUrl = WxQrCodeUtils.buildTemporaryQRCode(QrCodeTypeEnum.QR_STR_SCENE, ACTIVITY_KEY + fromUserName, 3600);
        WxUser userInfo = userService.getInfoByOpenId(fromUserName);
        String endPath = ImageUtils.imageSynthesis("http://agrienforce.lnkj0.com/api/dev/file/download?id=1781231042142150657",
                qrCodeUrl, userInfo.getAvatar());
        return WxMaterialUtils.uploadMaterialByFilePath(endPath);
    }

    @Override
    public String getRankingList() {
        String url = "http://" + REDIRECT_URI + "/follow/getRankingList";
        return String.format("点击链接 <a href=\"%s\">查看排行榜</a>", url);
    }

    @Override
    public String scanCodeAssistance(String toOpenId, String fromOpenId) {

        WxFollowInfo dbFollowInfo = followInfoService.getOne(Wrappers.lambdaUpdate(WxFollowInfo.class)
                .eq(WxFollowInfo::getOpenId, toOpenId)
                .eq(WxFollowInfo::getFollowOpenId, fromOpenId));

        DateTime date = DateUtil.date();
        boolean result = false;
        String resultMsg = "助力失败";
        if (dbFollowInfo == null) {
            result = followInfoService.save(new WxFollowInfo()
                    .setOpenId(toOpenId)
                    .setFollowOpenId(fromOpenId)
                    .setFollowDate(date));
            if (result) {
                // 给被助力者发送信息
                this.successfullyAssisted(toOpenId, fromOpenId);
                resultMsg = "助力成功";
            }
        } else {
            result = followInfoService.updateById(dbFollowInfo
                    .setFollowDate(date));
            if (result) {
                resultMsg = "已为好友助力，重复助力不加入统计";
            }
        }
        return resultMsg;
    }

    /**
     * 给被助力者发送信息
     *
     * @param toOpenId   被助力者openId
     * @param fromOpenId 助力者openId
     */
    private void successfullyAssisted(String toOpenId, String fromOpenId) {

        WxUser dbWxUser = userService.getInfoByOpenId(fromOpenId);

        long count = followInfoService.getCountByOpenId(toOpenId);

        if (dbWxUser != null) {
            WxSendMsgUtils.successfullyAssisted(toOpenId, dbWxUser.getNickName(), count, "第五级", "100");
        }
    }

}
